import Vue from "vue";
import ElementUI from "element-ui";
Vue.use(ElementUI);
const overstated = 401; //登陆过期
var reloading = false; //是否正在执行刷新页面逻辑
if (window.axios === undefined) {
	window.axios = require("axios");
	window.axios.defaults.baseURL = "/admin/";
	window.axios.defaults.headers.common["X-CSRF-TOKEN"] =
		window.Laravel === undefined ? LA.token : window.Laravel.csrfToken;
	window.axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
	/*window.axios.defaults.maxRedirects = 0;*/

	//拦截response，并作一些处理
	window.axios.interceptors.response.use(
		response => {
			//对返回的数据进行一些处理
			if (overstated == response.status) {
				//刷新，跳转到登陆界面
				window.location.href = "/admin/auth/logout";
			} else {
				return response;
			}
		},
		error => {
			//对返回的错误进行一些处理
			return Promise.reject(error);
		}
	);

	window.axios.wtCall = function(serverPath, method = "GET", params = null) {
		if (window.modulePrefix) {
			serverPath = window.modulePrefix + "/" + serverPath;
		}
		if (method == "DRONE") {
			if (params != null) {
				if (
					Object.prototype.toString.call(params) !== "[object String]"
				) {
					params = { data: JSON.stringify(params) };
				} else {
					params = { data: params };
				}
			}
			method = "POST";
		}
		let data = {
			path: serverPath,
			method: method
		};
		if (params != null) {
			data.params = params;
		}
		return this.post("transfer", data);
	};
}

function isSuccessful(httpCode) {
	if (Number(httpCode) >= 200 && Number(httpCode) < 300) {
		return true;
	}
	return false;
}

/**
 * 根据axios进行包装后的使用方便的请求接口
 */
function request(
	path,
	method,
	data,
	transfer,
	successCallback,
	errorCallback,
	returnAllData = false
) {
	let caller = null;
	if (transfer) {
		caller = window.axios.wtCall(path, method, data);
	} else {
		let options = {
			method: method,
			url: path
		};
		if (data != null) {
			if (method == "GET") {
				options.params = data;
			} else if (
				method == "POST" ||
				method == "PUT" ||
				method == "PATCH"
			) {
				options.data = data;
			} else {
				options.params = data;
			}
		}
		caller = window.axios(options);
	}
	caller
		.then(function(response) {
			let successful = true;
			if (!isSuccessful(response.status)) {
				successful = false;
			} else {
				if (transfer && !isSuccessful(response.data.status)) {
					successful = false;
				}
			}

			if (successful) {
				let data = null;
				if (transfer) {
					data = response.data.content;
				} else {
					if (returnAllData) {
						data = response.data;
					} else {
						data = response.data.data;
					}
				}
				safeInvokeCallback(successCallback, data, errorCallback);
			} else {
				if (response.data) {
					safeInvokeCallback(errorCallback, response.data);
				} else {
					safeInvokeCallback(errorCallback, "request failed");
				}
			}
		})
		.catch(function(error) {
			if (reloading) return;
			if (error.response && overstated == error.response.status) {
				reloading = true;
				Vue.prototype.$alert(
					error.response.data.message,
					"请重新登录",
					{
						confirmButtonText: "确定",
						callback: action => {
							setTimeout(_ => {
								window.location.href = "/admin/auth/logout";
							}, 400);
						}
					}
				);
			} else {
				safeInvokeCallback(errorCallback, error);
			}
		});
}

/**
 * 安全调用回调函数，回调函数出错时打印错误信息并调用errorCallback
 * @param {*} callback
 * @param {*} param
 * @param {*} errorCallback
 */
function safeInvokeCallback(callback, param, errorCallback = null) {
	try {
		callback(param);
	} catch (err) {
		console.error("Error happened in callback! ", err);
		if (errorCallback != null) {
			errorCallback(err);
		}
	}
}

export default request;
